package com.education.wisdom.controller.app;

import com.education.common.utils.ApiReturnObject;
import com.education.common.utils.DateLiuUtil;
import com.education.common.utils.StringUtils;
import com.education.config.BaiduAipContentCensor;
import com.education.wisdom.feign.UserFeign;
import com.education.wisdom.pojo.CatalogLive;
import com.education.wisdom.pojo.CommentsLive;
import com.education.wisdom.pojo.JrMoments;
import com.education.wisdom.pojo.JrMomentsThumbsUp;
import com.education.wisdom.service.ICatalogLiveService;
import com.education.wisdom.service.ICommentsLiveService;
import com.education.wisdom.service.IJrMomentsService;
import com.education.wisdom.service.IJrMomentsThumbsUpService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * 朋友圈 信息操作处理
 *
 * @author d
 * @date 2020-07-07
 */
@RestController
@RequestMapping("/jrMoments")
public class AppJrMomentsController {

    private final IJrMomentsService jrMomentsService;
    private final ICommentsLiveService commentsLiveService;
    private final IJrMomentsThumbsUpService thumbsUpService;
    private final UserFeign userFegin;
    private final ICatalogLiveService catalogLiveService;
    private final BaiduAipContentCensor baiduAipContentCensor;

    @Autowired
    public AppJrMomentsController(IJrMomentsService jrMomentsService,
                                  ICommentsLiveService commentsLiveService,
                                  IJrMomentsThumbsUpService thumbsUpService,
                                  @Qualifier("com.education.wisdom.feign.UserFeign") UserFeign userFegin,
                                  ICatalogLiveService catalogLiveService,
                                  BaiduAipContentCensor baiduAipContentCensor) {
        this.jrMomentsService = jrMomentsService;
        this.commentsLiveService = commentsLiveService;
        this.thumbsUpService = thumbsUpService;
        this.userFegin = userFegin;
        this.catalogLiveService = catalogLiveService;
        this.baiduAipContentCensor = baiduAipContentCensor;
    }

    /**
     * 拼接点赞人名字字符串
     */
    private String jointName(List<JrMomentsThumbsUp> list) {
        //拼接点赞人姓名字段
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            if (i == list.size() - 1) {
                //最后一条点赞记录
                stringBuilder.append(list.get(i).getSysRelName());
                return stringBuilder.toString();
            }
            stringBuilder.append(list.get(i).getSysRelName()).append(",");
        }
        return stringBuilder.toString();
    }

    /**
     * 判断是否点赞 是否评论
     */
    private String isSelect(List<?> t) {
        if (t.size() > 0) {
            return "1";
        }
        return "0";
    }

    /**
     * @param jrMoments
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    private PageInfo listGeneral(JrMoments jrMoments, String userId, Integer pageNum, Integer pageSize) {
        //根据userId catalogId  查询 创建时间 标题 内容  连接查询发布人头像 名字
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        jrMoments.setDeflag("2");
        List<JrMoments> list = jrMomentsService.selectJrMomentsListOther(jrMoments);
        for (JrMoments moments : list) {
            moments.setImgStringList(Lists.newArrayList());
            //格式化创建日期
            LocalDateTime ldt = moments.getCreateTime().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime();
            String dateTime = DateLiuUtil.getAllFormatterLocalMouthDateTime(ldt);
            moments.setCreateTimeString(dateTime);

            //如果内容为图片进行切割
            if ("2".equals(moments.getType())) {
                if (!"".equals(moments.getImages())) {
                    //图片 进行切割 设置参数
                    moments.setImgStringList(Arrays.asList(moments.getImages().split(",")));
                }
                moments.setImages("");
            }
            //是否评论 设置职业达人视频id  用户id
            CommentsLive commentsLive = CommentsLive.builder().plCreateuser(userId).plCatalogId(moments.getId()).build();
            //当前用户对当前职业达人视频的评论情况
            List<CommentsLive> commentsLives = commentsLiveService.selectCommentsLiveList(commentsLive);
            String select = isSelect(commentsLives);
            //是否评论状态
            moments.setIsComment(select);

            //是否点赞 设置职业达人视频id  用户id
            JrMomentsThumbsUp thumbsUp = JrMomentsThumbsUp.builder().delFlag("0").dzUserloginid(userId).dzLtid(moments.getId().toString()).build();
            List<JrMomentsThumbsUp> jrMomentsThumbsUps = thumbsUpService.selectJrMomentsThumbsUpList(thumbsUp);
            String select1 = isSelect(jrMomentsThumbsUps);
            //是否点赞状态
            moments.setIsThumbUp(select1);

            //评论数   查询出当前职业达人视频的评论列表
            CommentsLive commentsLive1 = CommentsLive.builder().plCatalogId(moments.getId()).build();
            List<CommentsLive> commentsLives1 = commentsLiveService.selectCommentsLiveList(commentsLive1);
            moments.setCommentNum(commentsLives1.size());
            //点赞数
            JrMomentsThumbsUp thumbsUp1 = JrMomentsThumbsUp.builder().dzLtid(moments.getId().toString()).delFlag("0").build();
            List<JrMomentsThumbsUp> jrMomentsThumbsUps1 = thumbsUpService.selectJrMomentsThumbsUpListOther(thumbsUp1);
            moments.setThumbUpNum(jrMomentsThumbsUps1.size());
            //点赞人名称字符串
            String s = jointName(jrMomentsThumbsUps1);
            moments.setNameString(s);
            moments.setCommentsLive(new CommentsLive());
            if (commentsLives1.size() > 0) {
                //取出第一条评论
                CommentsLive live = commentsLives1.get(0);
                if (StringUtils.isNotNull(live.getPlCreateuser())) {
                    //评论人头像 以及 评论人姓名
                    Map<String, String> map = userFegin.selectOneUser(live.getPlCreateuser());
                    live.setUserName(map.get("sysRelName"));
                    live.setUserIcoUrl(map.get("sysIco"));
                } else {
                    live.setUserName("匿名");
                    live.setUserIcoUrl("1595899770924.jpg");
                }
                moments.setCommentsLive(live);
            }
        }
        return new PageInfo<>(list);
    }

    /**
     * 利用专业分类可进行筛选
     * 以及最近一条评论 以及评论数
     * 参数写具体用到的字段
     * 发表人的 头像 姓名
     * 创建时间 标题 视频或多张图片
     * 展示评论数 点赞数
     * 列表每条数据判断 当前登录人是否评论 是否点赞的状态
     * 根据当前登录人的id筛选出我发布的职业达人视频
     *
     */
    /**
     * 学生APP-查询职业达人视频列表
     *
     * @param jrMoments
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/list")
    public ApiReturnObject list(JrMoments jrMoments, Integer pageNum, Integer pageSize) {
        if (jrMoments.getUserId() == null) {
            return new ApiReturnObject("201", "缺少userId参数", "");
        }
        String userId = jrMoments.getUserId();
        //清空 不然查回来的是我的相关列表信息
        //jrMoments.setUserId(null);
        PageInfo pageInfo = listGeneral(jrMoments, userId, pageNum, pageSize);
        return new ApiReturnObject("200", "查询成功", pageInfo);
    }

    /**
     * 利用专业分类可进行筛选
     * 以及最近一条评论 以及评论数
     * 参数写具体用到的字段
     * 发表人的 头像 姓名
     * 创建时间 标题 视频或多张图片
     * 展示评论数 点赞数
     * 列表每条数据判断 当前登录人是否评论 是否点赞的状态
     * 根据当前登录人的id筛选出我发布的职业达人视频
     * 查询职业达人视频列表
     */
    @GetMapping("/listOnlyMy")
    public ApiReturnObject listOnlyMy(JrMoments jrMoments, Integer pageNum, Integer pageSize) {
        if (jrMoments.getUserId() == null || "".equals(jrMoments.getUserId())) {
            return new ApiReturnObject("201", "缺少userId参数", "");
        }
        String userId = jrMoments.getUserId();
        //清空 不然查回来的是我的相关列表信息
        PageInfo pageInfo = listGeneral(jrMoments, userId, pageNum, pageSize);
        return new ApiReturnObject("200", "查询成功", pageInfo);
    }


    /**
     * 详情接口编写
     * 发布人的头像 姓名 创建时间
     * 标题 一个视频或多张图片
     * 点赞人的姓名 用逗号隔开
     * 评论列表 评论人的 头像 姓名 内容 创建时间
     * 当前登录人是否评论 是否点赞的状态
     */
    @GetMapping("/selectOne")
    public ApiReturnObject selectOne(Integer id, String userId) {
        if (id != null) {
            //职业达人视频详情 及 发布人头像 名称
            JrMoments jrMoments = jrMomentsService.selectJrMomentsByIdother(id);
            //设置 图片集合 成为空数组
            jrMoments.setImgStringList(Lists.newArrayList());
            jrMoments.setCommentsLives(Lists.newArrayList());
            String s = "2";
            //如果内容为图片进行切割
            if (s.equals(jrMoments.getType())) {
                if (!"".equals(jrMoments.getImages())) {
                    //图片 进行切割 设置参数
                    jrMoments.setImgStringList(Arrays.asList(jrMoments.getImages().split(",")));
                }
                jrMoments.setImages("");
            }
            //格式化创建日期
            LocalDateTime ldt1 = jrMoments.getCreateTime().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime();
            String dateTime1 = DateLiuUtil.getAllFormatterLocalMouthDateTime(ldt1);
            jrMoments.setCreateTimeString(dateTime1);
            //评论当前职业达人视频 所有的评论  评论人头像 姓名 评论内容 创建时间
            CommentsLive commentsLive = CommentsLive.builder().plCatalogId(id).build();
            List<CommentsLive> commentsLives = commentsLiveService.selectCommentsLiveListOther(commentsLive);
            if (commentsLives.size() > 0) {
                for (CommentsLive live : commentsLives) {
                    //格式化评论列表的创建时间
                    LocalDateTime ldt = live.getPlCreatetime().toInstant()
                            .atZone(ZoneId.systemDefault())
                            .toLocalDateTime();
                    String dateTime = DateLiuUtil.getAllFormatterLocalMouthDateTime(ldt);
                    live.setPlCreateTimeString(dateTime);
                }
                jrMoments.setCommentsLives(commentsLives);
            }
            //点赞人姓名字符串
            JrMomentsThumbsUp thumbsUp = JrMomentsThumbsUp.builder().dzLtid(id.toString()).delFlag("0").build();
            List<JrMomentsThumbsUp> jrMomentsThumbsUps = thumbsUpService.selectJrMomentsThumbsUpListOther(thumbsUp);
            //点赞人名称字符串
            String s1 = jointName(jrMomentsThumbsUps);
            jrMoments.setNameString(s1);
            //点赞数
            jrMoments.setThumbUpNum(jrMomentsThumbsUps.size());
            //是否评论 设置职业达人视频id  用户id
            CommentsLive commentsLive1 = CommentsLive.builder().plCreateuser(userId).plCatalogId(id).build();
            //当前用户对当前职业达人视频的评论情况
            List<CommentsLive> commentsLives1 = commentsLiveService.selectCommentsLiveList(commentsLive1);
            //评论数   查询出当前职业达人视频的评论列表
            jrMoments.setCommentNum(commentsLives1.size());
            String select = isSelect(commentsLives1);
            //是否评论状态
            jrMoments.setIsComment(select);
            //是否点赞 设置职业达人视频id  用户id
            JrMomentsThumbsUp thumbsUp1 = JrMomentsThumbsUp.builder().delFlag("0").dzUserloginid(userId).dzLtid(id.toString()).build();
            List<JrMomentsThumbsUp> jrMomentsThumbsUps1 = thumbsUpService.selectJrMomentsThumbsUpList(thumbsUp1);
            String select1 = isSelect(jrMomentsThumbsUps1);
            //是否点赞状态
            jrMoments.setIsThumbUp(select1);
            return new ApiReturnObject("200", "查询成功", jrMoments);
        }
        return new ApiReturnObject("201", "缺少参数id", "");
    }

    public JrMoments selectOne2(Integer id, String userId) {
        //职业达人视频详情 及 发布人头像 名称
        JrMoments jrMoments = jrMomentsService.selectJrMomentsByIdother(id);
        //点赞人姓名字符串
        JrMomentsThumbsUp thumbsUp = JrMomentsThumbsUp.builder().dzLtid(id.toString()).delFlag("0").build();
        List<JrMomentsThumbsUp> jrMomentsThumbsUps = thumbsUpService.selectJrMomentsThumbsUpListOther(thumbsUp);
        //点赞人名称字符串
        String s1 = jointName(jrMomentsThumbsUps);
        jrMoments.setNameString(s1);
        //点赞数
        jrMoments.setThumbUpNum(jrMomentsThumbsUps.size());
        //是否点赞 设置职业达人视频id  用户id
        JrMomentsThumbsUp thumbsUp1 = JrMomentsThumbsUp.builder().delFlag("0").dzUserloginid(userId).dzLtid(id.toString()).build();
        List<JrMomentsThumbsUp> jrMomentsThumbsUps1 = thumbsUpService.selectJrMomentsThumbsUpList(thumbsUp1);
        String select1 = isSelect(jrMomentsThumbsUps1);
        //是否点赞状态
        jrMoments.setIsThumbUp(select1);
        return jrMoments;
    }


    /**
     * 分类列表查询
     */
    @GetMapping("classifyList")
    public ApiReturnObject classifyList(String userId, String type) {
        HashMap<String, Object> map = Maps.newHashMap();
        //全部分类
        CatalogLive catalogLive = CatalogLive.builder().delFlag("0").build();
        List<CatalogLive> catalogLives = Lists.newArrayList();
        //添加全部选项
        catalogLives.add(CatalogLive.builder().catalogId(0).name("全部专业").build());
        List<CatalogLive> list1 = catalogLiveService.selectCatalogLiveList(catalogLive);
        catalogLives.addAll(list1);
        if (catalogLives.size() > 0) {
            map.put("catalogLives", catalogLives);
        } else {
            map.put("catalogLives", Lists.newArrayList());
        }
        String s = "1";
        if (s.equals(type)) {
//            map.put("catalogLivesPart", Lists.newArrayList());
            //去掉第一条的全部分类
            catalogLives.remove(0);
            map.put("catalogLives", catalogLives);
            return new ApiReturnObject("200", "查询成功", map);
        }
        return new ApiReturnObject("200", "查询成功", map);
    }


    /**
     * 新增保存职业达人视频
     * 发布职业达人视频
     * 文本内容
     * 内容类型
     * 有可能是一个视频    有可能是多张图片
     * 选择分类 分类的id
     * 参数: userId   catalogId   type    标题:content  视频:images  图片:ingStringList
     */
    @PostMapping("/add")
    public ApiReturnObject addSave(JrMoments jrMoments) {
        //判断内容类型 1视频2图片  todo 文字content 图片 视频images
        List<String> imgStringList = jrMoments.getImgStringList();
        String resType = "2";
        //添加多张图片路径拼接字符串
        if (resType.equals(jrMoments.getType()) && imgStringList != null && imgStringList.size() > 0) {
            //拼接字符串
            List<String> list = jrMoments.getImgStringList();
            if (list.size() > 0) {
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < list.size(); i++) {
                    if (i == list.size() - 1) {
                        //集合中的最后一个元素
                        stringBuilder.append(list.get(i));
                    } else {
                        stringBuilder.append(list.get(i)).append(",");
                    }
                }
                jrMoments.setImages(stringBuilder.toString());
            }
        }
        jrMoments.setCreateTime(new Date());
        jrMoments.setDeflag("2");
        List<String> resList = Arrays.asList(jrMoments.getImages().split(","));
        if (StringUtils.isNotBlank(jrMoments.getContent()) && (baiduAipContentCensor.AipText(jrMoments.getContent()) == 2)) {
            QiniuUtil.deleteFileFromQinius(resList);
            return new ApiReturnObject("201", "动态内容不适发布失败", "动态内容不适发布失败");
        }
        int i = jrMomentsService.insertJrMoments(jrMoments);
        Integer id = jrMoments.getId();
        if (jrMoments.getType().equals(resType)) {
            baiduAipContentCensor.batchAipImage(jrMoments.getImages(), "jr_moments", id);
        } else {
            baiduAipContentCensor.singleFileAddSave(jrMoments.getImages(), "jr_moments", "2", id);
        }
        return new ApiReturnObject("200", "添加成功", "");
        /*//判断内容类型
        String s = "2";
        //添加多张图片路径拼接字符串
        if (s.equals(jrMoments.getType()) && jrMoments.getImgStringList() != null && jrMoments.getImgStringList().size() > 0) {
            //拼接字符串
            List<String> list = jrMoments.getImgStringList();
            if (list.size() > 0) {
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < list.size(); i++) {
                    if (i == list.size() - 1) {
                        //集合中的最后一个元素
                        stringBuilder.append(list.get(i));
                    } else {
                        stringBuilder.append(list.get(i)).append(",");
                    }
                }
                jrMoments.setImages(stringBuilder.toString());
            }
        }
        jrMoments.setCreateTime(new Date());
        jrMoments.setDeflag("2");
        jrMomentsService.insertJrMoments(jrMoments);
        return new ApiReturnObject("200", "添加成功", "");*/
    }

    /**
     * jr_comments_live
     * 评论功能
     * 职业达人视频id     pl_catalogId
     * 评论内容           pl_text
     * 创建人             pl_createUser
     * 创建时间           pl_createTime
     */
    @PostMapping("addComment")
    public ApiReturnObject comment(CommentsLive commentsLive) {
        if (commentsLive.getPlCreateuser() != null) {
            commentsLive.setPlCreatetime(new Date());
            if (baiduAipContentCensor.AipText(commentsLive.getPlText()) == 2) {
                return new ApiReturnObject("201", "评论违规", "评论违规");
            }
            commentsLiveService.insertCommentsLive(commentsLive);
            //评论数
            CommentsLive commentsLive1 = CommentsLive.builder().plCatalogId(commentsLive.getPlCatalogId()).build();
            List<CommentsLive> commentsLives1 = commentsLiveService.selectCommentsLiveList(commentsLive1);
            int size = commentsLives1.size();
            return new ApiReturnObject("200", "评论成功", size, "");
        }
        return new ApiReturnObject("201", "缺少参数plCreateUser", "");
    }

    /**
     * 获取点赞数
     */
    private Integer getLikeNum(String id) {
        //点赞数
        JrMomentsThumbsUp thumbsUp1 = JrMomentsThumbsUp.builder().dzLtid(id).delFlag("0").build();
        List<JrMomentsThumbsUp> jrMomentsThumbsUps1 = thumbsUpService.selectJrMomentsThumbsUpListOther(thumbsUp1);
        return jrMomentsThumbsUps1.size();
    }

    /**
     * jr_moments_thumbs_up
     * 点赞功能 like  取消点赞 unlike
     * dz_userLoginId  点赞人id
     * dz_thumbsUpTime 点赞时间
     * dz_ltid         职业大人视频id
     */
    @PostMapping("/addLikeVideo")
    public ApiReturnObject likeVideo(JrMomentsThumbsUp momentsThumbsUp) {
        //判断是否已经点赞  是 取消点赞 否 进行点赞
        JrMomentsThumbsUp thumbsUp = JrMomentsThumbsUp.builder().dzUserloginid(momentsThumbsUp.getDzUserloginid()).dzLtid(momentsThumbsUp.getDzLtid()).build();
        List<JrMomentsThumbsUp> jrMomentsThumbsUps = thumbsUpService.selectJrMomentsThumbsUpList(thumbsUp);
        if (jrMomentsThumbsUps.size() > 0) {
            //获取第一条记录  判断delFlag的状态
            JrMomentsThumbsUp thumbs = jrMomentsThumbsUps.get(0);
            if (!"".equals(thumbs.getDelFlag())) {
                String s = "0";
                if (s.equals(thumbs.getDelFlag())) {
                    //0 已经点赞 取消点赞 改变状态
                    thumbs.setDelFlag("1");
                    thumbsUpService.updateJrMomentsThumbsUp(thumbs);
                    //返回点赞数  职业达人视频id
                    Integer likeNum = getLikeNum(momentsThumbsUp.getDzLtid());
                    //
                    JrMoments jrMoments = selectOne2(Integer.parseInt(momentsThumbsUp.getDzLtid()), momentsThumbsUp.getDzUserloginid());
                    return new ApiReturnObject("200", "取消点赞成功", likeNum, jrMoments);
                } else {
                    // 已取消点赞    改为点赞状态
                    thumbs.setDelFlag("0");
                    thumbsUpService.updateJrMomentsThumbsUp(thumbs);
                    //返回点赞数
                    Integer likeNum = getLikeNum(momentsThumbsUp.getDzLtid());
                    //
                    JrMoments jrMoments = selectOne2(Integer.parseInt(momentsThumbsUp.getDzLtid()), momentsThumbsUp.getDzUserloginid());
                    return new ApiReturnObject("200", "点赞成功", likeNum, jrMoments);
                }
            }
        }
        //没有点赞 进行点赞操作   添加点赞记录
        momentsThumbsUp.setDzThumbsuptime(new Date());
        momentsThumbsUp.setDelFlag("0");
        thumbsUpService.insertJrMomentsThumbsUp(momentsThumbsUp);
        //返回点赞数
        Integer likeNum = getLikeNum(momentsThumbsUp.getDzLtid());
        //查详情
        JrMoments jrMoments = selectOne2(Integer.parseInt(momentsThumbsUp.getDzLtid()), momentsThumbsUp.getDzUserloginid());
        return new ApiReturnObject("200", "点赞成功", likeNum, jrMoments);
    }


    /**
     * 修改保存职业达人视频
     */
    @PostMapping("/update")
    public ApiReturnObject editSave(JrMoments jrMoments) {
        if (jrMoments.getId() != null) {
            jrMomentsService.updateJrMoments(jrMoments);
            return new ApiReturnObject("200", "修改成功", "");
        }
        return new ApiReturnObject("201", "缺少参数id", "");
    }

    /**
     * 删除职业达人视频
     */
    @PostMapping("/del")
    public ApiReturnObject remove(JrMoments jrMoments) {
        if (jrMoments.getId() != null) {
            //删除评论关联数据
            commentsLiveService.deleteCommentsLiveById(jrMoments.getId().toString());
            //删除点赞关联数据
            thumbsUpService.deleteJrMomentsThumbsUpByIds(jrMoments.getId().toString());
            //删除职业达人视频信息
            JrMoments jrMoments1 = jrMomentsService.selectJrMomentsById(jrMoments.getId());
            if (jrMoments1.getImages() != null && !"".equals(jrMoments1.getImages())) {
                if (jrMoments1.getImages().contains(",")) {
                    //切割批量删除
                    List<String> stringList = Arrays.asList(jrMoments1.getImages().split(","));
                    QiniuUtil.deleteFileFromQinius(stringList);
                } else {
                    QiniuUtil.deleteFileFromQiniu(jrMoments1.getImages());
                }
            }
            jrMomentsService.deleteJrMomentsById(jrMoments.getId());
            return new ApiReturnObject("200", "删除成功", "");
        }
        return new ApiReturnObject("201", "缺少参数", "");
    }
}